package com.learn.pass;

public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        // 单独情况
        // 如果strs只有一个元素直接返回就可以了
        int strsLen = strs.length;
        if (strsLen == 1) {
            return strs[0];
        }

        int maxLen = Integer.MAX_VALUE;
        for (int i = 1; i < strsLen; i++) {
            // 计算当前最长公共前缀
            int strLen = Math.min(strs[0].length(), strs[i].length());
            int j = 0;
            for (; j < strLen; j++) {
                if (strs[0].charAt(j) != strs[i].charAt(j)) {
                    break;
                }
            }
            //结算，下一个
            maxLen = Math.min(maxLen, j);
        }

        return strs[0].substring(0, maxLen);
    }
}
